package com.etlmaster.executor.scheduler.utils;

import java.util.Map;
import java.util.concurrent.Callable;

import org.springframework.web.client.RestTemplate;

import com.etlmaster.executor.agent.Agents;
import com.etlmaster.executor.scheduler.Proc;
import com.etlmaster.executor.scheduler.ScheduleServer;
import com.etlmaster.executor.utils.JsonHelper;
import com.etlmaster.executor.utils.LogWriter;

/**
 * @author Larry
 * @date 2017-04-14 线程实例
 */
public class CallResetService implements Callable<CallableResult> {

	public int FAILURE = 1;
	public static final String SUCCESS_MSG = "success";
	public static final int SUCCESS = 0;

	private Agents agent;
	private Proc proc;
	private RestTemplate template;

	private String url;

	public CallResetService(String url, Agents agent, Proc proc,
			RestTemplate template) {
		this.agent = agent;
		this.proc = proc;
		this.template = template;
		this.url = url;
	}

	public CallableResult call() throws Exception {
		CallableResult result = null;

		try {
			// String
			// url="http://"+agent.getHost()+"/etlmaster/startjob?jobjson="+proc.getRunParam()
			// ;
			LogWriter.addLog("INFO", "调用服务:{}", url);
			String rtn = template.getForObject(url, String.class,
					new String[] {});
			LogWriter.addLog("INFO", rtn);
			Map<String,Object> map=(Map<String, Object>) JsonHelper.getInstance().read(rtn);
			int rtnCode=(int) map.get("rtnCode");
			String rtnMsg=(String) map.get("rtnMsg");

			result = new CallableResult(rtnCode, rtnMsg);

		} catch (Exception e) {
			e.printStackTrace();
			result = new CallableResult(FAILURE, e.getMessage());
		}

		if (proc != null) {
			ScheduleServer.getLock().lock();
			agent.getRunningProcs().remove(proc);
			ScheduleServer.getAgentNotEmpty().signal();
			ScheduleServer.getLock().unlock();
		}
		return result;
	}
}
